import dayjs from "dayjs";
import customerTransferForm from "@/components/customerTransfer/index.vue";

import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { tags_list } from "@/api/tag";
import { user_list } from "@/api/user";
import { customerSalesmanData, customerLeaderData_distribute_batch, customerLeaderData_distribute, customerReceive } from "@/api/customer";
import { addDialog } from "@/components/ReDialog";
import { type Ref, reactive, ref, onMounted, h, toRaw, computed } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";

import { useUserStoreHook } from "@/store/modules/user";

export function useRole(detailRef: Ref) {
  /** 页面元素权限 */
  const auth_element = computed(() => {
    return useUserStoreHook()?.auth_element;
  });

  const permissions = reactive({
    is_search_keyword: false, // 客户名称/企业名称
    is_search_tag: false, // 客户标签
    is_search_source: false, // 数据来源
    is_search_staff: false, // 前跟进人
    is_search_entryAt: false, // 入池时间
    is_search_entryTimes: false, // 入池次数

    is_single_see: false, // 查看客户详情
    is_single_gain: false, // 领取

    is_batch_dispatch: false, // 批量分配
    is_batch_gain: false, // 批量领取
  })
  
  const shortcuts = [
    {
      text: "上周",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        return [start, end];
      }
    },
    {
      text: "上个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        return [start, end];
      }
    },
    {
      text: "三个月前",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        return [start, end];
      }
    }
  ];
  const labelList = ref([]);
  const sourceList = ref([
    {
      value: "exchange",
      label: "兑领"
    },
    {
      value: "third",
      label: "第三方自导入"
    }
  ]);
  /** 部门 */
  const department_belong = computed(() => {
    return useUserStoreHook()?.department_belong;
  });
  const userList = ref([]);
  const form = reactive({
    keyword: "",
    tag_id: "",
    source_by: "",
    target_staff_id: "",
    insea_at: "",
    insea_times: "",
    status: "insea",
    page: 1,
    size: 10
  });
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns = reactive<TableColumnList>([
    {
      type: "selection",
      align: "left"
    },
    {
      label: "企业名称",
      prop: "company_name",
      minWidth: 200
    },
    {
      label: "客户名称",
      prop: "name",
      minWidth: 100
    },
    {
      label: "联系电话",
      prop: "phone",
      minWidth: 140,
      formatter: ({ phone }) => {
        // 检查 phone 是否存在且为字符串或数字
        if (phone === null || phone === undefined) return "";
        const phoneStr = String(phone);
        // 确保是11位手机号格式
        if (!/^\d{11}$/.test(phoneStr)) return phoneStr;
        return phoneStr.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
      }
    },
    {
      label: "地区",
      prop: "address_path",
      minWidth: 180
    },
    {
      label: "客户标签",
      prop: "tag_ids",
      minWidth: 140,
      formatter: ({ tag_ids }) => {
        if (!tag_ids) return "";
        let tagIds = tag_ids.split(",").map(item => item.replaceAll("_", ""));
        return tagIds.map(item => labelList.value.find(tag => tag.id === item)?.name).join(",");
      }
    },
    {
      label: "数据来源",
      prop: "source_by",
      minWidth: 160,
      formatter: ({ source_by }) => {
        if (!source_by) return "";
        return sourceList.value.filter(item => item.value == source_by)[0].label;
      }
    },
    {
      label: "累计进入公海次数",
      prop: "insea_times",
      minWidth: 140
    },
    {
      label: "进入公海时间",
      prop: "insea_at",
      minWidth: 150,
      formatter: ({ insea_at }) => insea_at == 0 ? "" : dayjs.unix(insea_at).format("YYYY-MM-DD")
    },
    {
      label: "查看",
      fixed: "right",
      slot: "operation"
    }
  ]);
  
  const tableRef = ref();
  const multipleSelection = ref([]);
  const detailInfo = ref();

  function lookCustomer(row) {
    detailInfo.value = row;
    detailRef.value.openDrawer(row.id);
  }

  function handleSizeChange(val: number) {
    form.size = val;
    pagination.pageSize = val;
    onSearch(); // 刷新表格数据
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    pagination.currentPage = val;
    onSearch(); // 刷新表格数据
  }

  function handleSelectionChange(val) {
    multipleSelection.value = val;
  }

  function handleSelectionClear() {
    const { toggleRowSelection, clearSelection } = tableRef.value.getTableRef();
    clearSelection();
  }

  // 分配给组员
  const customerTransferFormRef = ref();
  function transferClick() {
    addDialog({
      title: "分配给组员",
      props: {
        formInline: {
          leader: null,
          leader_name: "",
        }
      },
      width: "800px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(customerTransferForm, { ref: customerTransferFormRef, formInline: null } ),
      beforeSure: (done, { options }) => {
        const curData = options.props.formInline
        if (curData.leader) {
          if (multipleSelection.value.length) {
            customerLeaderData_distribute_batch({
              ids: multipleSelection.value.map(item => `${item.id}:${item.table_at}:${item.version}`).join(","),
              to_target_staff_id: curData.leader
            }).then(res => {
              if (res.code == 1000) {
                message(`操作成功！`, { type: "success" });
                setTimeout(() => {
                  done(); // 关闭弹框
                  multipleSelection.value = []
                  onSearch();
                }, 1000);
              } else {
                message(res.msg, { type: "error" });
              }
            });
          } else {
            customerLeaderData_distribute({
              id: detailInfo.value.id,
              table_at: detailInfo.value.table_at,
              version: detailInfo.value.version,
              to_target_staff_id: curData.leader
            }).then(res => {
              if (res.code == 1000) {
                message(`操作成功！`, { type: "success" });
                setTimeout(() => {
                  done(); // 关闭弹框
                  detailRef.value.closeDrawer();
                  onSearch();
                }, 1000);
              } else {
                message(res.msg, { type: "error" });
              }
            });
          }
        } else {
          message(`请选择人员！`, { type: "error" });
        }
      }
    });
  }

  // 领取
  function receiveClick(row) {
    ElMessageBox.confirm(
      row ? "确定执行领取？" : "确定进行本次批量领取？",
      "重要提示",
      {
        type: "warning"
      }
    )
      .then(() => {
        if (row) {
          if (row == "detail") {
            customerReceive({
              ids: `${detailInfo.value.id}:${detailInfo.value.table_at}:${detailInfo.value.version}`
            }).then(res => {
              if (res.code == 1000) {
                message(`操作成功！`, {
                  type: "success"
                });
                setTimeout(() => {
                  detailRef.value.closeDrawer();
                  onSearch(); // 刷新表格数据
                }, 1000);
              } else {
                message(res.msg, { type: "error" });
              }
            });
          } else {
            customerReceive({
              ids: `${row.id}:${row.table_at}:${row.version}`
            }).then(res => {
              if (res.code == 1000) {
                message(`操作成功！`, {
                  type: "success"
                });
                setTimeout(() => {
                  onSearch(); // 刷新表格数据
                }, 1000);
              } else {
                message(res.msg, { type: "error" });
              }
            });
          }
        } else {
          let curForm: any = {};
          curForm.ids = multipleSelection.value
            .map(item => `${item.id}:${item.table_at}:${item.version}`)
            .join(",");
          customerReceive(curForm).then(res => {
            if (res.code == 1000) {
              message(`操作成功！`, {
                type: "success"
              });
              setTimeout(() => {
                multipleSelection.value = [];
                onSearch(); // 刷新表格数据
              }, 1000);
            } else {
              message(res.msg, { type: "error" });
            }
          });
        }
      })
      .catch(() => {});
  }

  function handleOffline(row) {
    message(`${row.username}已被强制下线`, { type: "success" });
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    
    let queryFrom = { ...form };
    if (queryFrom.insea_at.length) {
      let startTime = dayjs(queryFrom.insea_at[0]).format("YYYY-MM-DD");
      let endTime = dayjs(queryFrom.insea_at[1]).format("YYYY-MM-DD");
      queryFrom.insea_at = `${startTime},${endTime}`;
    }

    const result = await customerSalesmanData(toRaw(queryFrom));

    dataList.value = result.data.list;
    pagination.total = result.data.total;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    getLabelList();
    getUserList();
    onSearch();

    /** 筛选完-页面元素权限 */
    if (auth_element.value) {
      // 查询 onpage 为 "/customerData/index" 的所有数据
      const homeData = Object.entries(JSON.parse(auth_element.value)).filter(([key, value]) => value.onpage === "/customerData/index");
      // 转换为对象形式
      const homeDataObj: any = Object.fromEntries(homeData);
      
      // opensea_search
      if (homeDataObj.opensea_search) {
        // search
        if (homeDataObj.opensea_search.search && homeDataObj.opensea_search.search.length) {
          let permiss = homeDataObj.opensea_search.search.join(',')
          permissions.is_search_keyword = permiss.includes('keyword') ? true : false
          permissions.is_search_tag = permiss.includes('tag') ? true : false
          permissions.is_search_source = permiss.includes('source') ? true : false
          permissions.is_search_staff = permiss.includes('staff') ? true : false
          permissions.is_search_entryAt = permiss.includes('entryAt') ? true : false
          permissions.is_search_entryTimes = permiss.includes('entryTimes') ? true : false
        }
        // single
        if (homeDataObj.opensea_search.single && homeDataObj.opensea_search.single.length) {
          let permiss = homeDataObj.opensea_search.single.join(',')
          permissions.is_single_see = permiss.includes('see') ? true : false
          permissions.is_single_gain = permiss.includes('gain') ? true : false
        }
        // batch
        if (homeDataObj.opensea_search.batch && homeDataObj.opensea_search.batch.length) {
          let permiss = homeDataObj.opensea_search.batch.join(',')
          permissions.is_batch_dispatch = permiss.includes('dispatch') ? true : false
          permissions.is_batch_gain = permiss.includes('gain') ? true : false
        }

        let tableRemove = homeDataObj.opensea_search.remove ? homeDataObj.opensea_search.remove.split(',') : []
        for (let i = 0; i < tableRemove.length; i++) {
          for (let a = 0; a < columns.length; a++) {
            if (columns[a].prop == tableRemove[i]) {
              columns.splice(a, 1)
            }
          }
        }
      }
    }
  });

  // 获取客户标签
  function getLabelList() {
    tags_list({
      page: 1,
      pagesize: 999,
      status: 1
    }).then(res => {
      labelList.value = res.data;
    });
  }

  // 获取用户列表
  function getUserList() {
    user_list({
      page: 1,
      pagesize: 999,
      status: "1",
      department_belong: department_belong.value,
      not_me: 1,
    }).then(res => {
      userList.value = res.data;
    });
  }

  return {
    permissions,

    shortcuts,
    labelList,
    userList,
    sourceList,
    form,
    loading,
    columns,
    dataList,
    pagination,
    tableRef,
    multipleSelection,

    transferClick,
    receiveClick,

    onSearch,
    resetForm,
    lookCustomer,
    handleOffline,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    handleSelectionClear
  };
}
